using Avalonia.Xaml.Interactivity;
using KinonekoSoftware.CodariaDB.Documents.Templates;
using KinonekoSoftware.Foundation.UI.Controls;
using KinonekoSoftware.Foundation.UI.Controls.Selectors;

using Application = Avalonia.Application;

namespace KinonekoSoftware.Studio.Resources.Behaviors
{
    public sealed class FindFeatureIconBehavior : Behavior<Iconify>
    {
        public static readonly Dictionary<string, Geometry> _geometries = new Dictionary<string, Geometry>();
        private static         Geometry                     _setting;
        
        protected override void OnAttached()
        {
            if (AssociatedObject is null)
            {
                return;
            }

            //
            //
            AssociatedObject.DataContextChanged += OnLoaded;

            base.OnAttached();
        }

        protected override void OnDetaching()
        {
            if (AssociatedObject is null)
            {
                return;
            }

            //
            //
            AssociatedObject.DataContextChanged -= OnLoaded;
            base.OnDetaching();
        }

        private void OnLoaded(object sender, EventArgs e)
        {

            var current = AssociatedObject;
            var parent  = Xaml.GetParent<ForestListBox>(current);

            if (current is null || parent is null)
            {
                return;
            }

            if (current.DataContext is not DataPartComponent component)
            {
                return;
            }


            var      icon = DataPart.GetIconName(component.Type);
            Geometry geometry;

            if (string.IsNullOrEmpty(icon))
            {
                icon         = "Setting";
                _setting     = parent.FindResource(icon) as Geometry ?? Application.Current!.Resources[icon] as Geometry;
                geometry     = _setting;
                current.Icon = geometry;
                return;
            }

            if (!_geometries.TryGetValue(icon, out  geometry))
            {
                if (geometry is null)
                {
                    return;
                }

                geometry = parent.FindResource(icon) as Geometry ?? Application.Current!.Resources[icon] as Geometry;
                _geometries.TryAdd(icon, geometry);
            }

            current.Icon = geometry;
        }
    }
}